<?php
/**
 * Notes:
 * User: ysian
 * Time: 15:54
 * @return
 */

namespace Ysian\Alipaysdk\tools;

class Str
{
    /**
     * @desc 随机获取字符串长度
     * @param $len 长度
     * @param string $type 有N(数字),L(小写字符),U(大写字母),单个或者组合获取字符串,默认为全部 ,S(特殊字符)由标识参数special=true来获取
     * @return string
     */
    public static function getRandomStr($len, $type ='all', $special=false)
    {
        $N = ['0','1','2','3','4','5','6','7','8','9'];
        $L = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        $U = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

        switch($type)
        {
            case 'N':
                $chars = $N;
                break;
            case 'NL':
                $chars = array_merge($N,$L);
                break;
            case 'NU':
                $chars = array_merge($N,$U);
                break;
            case 'LN':
                $chars = array_merge($L,$N);
                break;
            case 'LU':
                $chars = array_merge($L,$U);
                break;
            case 'UN':
                $chars = array_merge($U,$N);
                break;
            case 'UL':
                $chars = array_merge($U,$L);
                break;
            case 'NLU':
                $chars = array_merge($N,$L,$U);
                break;
            case 'LNU':
                $chars = array_merge($L,$N,$U);
                break;
            case 'UNL':
                $chars = array_merge($U,$N,$L);
                break;
            default:
                $chars = array_merge($L,$U,$N);
                break;
        }
        if($special===true) $chars = array_merge($chars,['!','@','#','$','?','|','{','/',':', ';','%','^','&','*','(',')','-','_','[',']','}','<','>','~','+','=',',','.']);

        shuffle($chars); //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[$i];
        }
        return $str;
    }

    public static function removeSpecialStr($str)
    {
        $strlen = mb_strlen($str);
        $newStr = '';
        for ($i=0; $i < $strlen ; $i++) {
            $str_i = mb_substr($str,$i,1);
            if(preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",$str_i)){
                $newStr .= $str_i;
            }
        }
        return $newStr;
    }

    /**
     * @desc 获取加密字符串
     * @param array $param
     * @return string
     */
    public static function getSignStr($param)
    {
        $str = '';
        ksort($param);
        foreach ($param as $k => $v) {
            if (is_array($v)) {
                $str .= $k . '=' . json_encode($v) . '&';
            } elseif (is_bool($v)) {
                $str .= $k . '=' . ($v ? "true" : "false") . '&';
            } elseif($v) {
                $str .= $k . '=' . $v . '&';
            }
        }
        return rtrim($str, '&');
    }

}